package cn.itzzx.lagou.filter;

import cn.itzzx.lagou.service.UserFeignClientService;
import io.github.bucket4j.Bandwidth;
import io.github.bucket4j.Bucket;
import io.github.bucket4j.Bucket4j;
import io.github.bucket4j.Refill;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.time.Duration;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 全局过滤器 实现{@link GlobalFilter}接口 和 {@link Ordered}接口即可
 * <p>
 * <p>
 * 过滤器功能描述 : 验证用户token
 *
 * @author Martin
 * @since 1.0
 */
@Component
public class TokenGlobalGatewayFilter implements GlobalFilter, Ordered {
    @Resource
    private UserFeignClientService userFeignClientService;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpResponse response = exchange.getResponse();
        MultiValueMap<String, HttpCookie> cookies = exchange.getRequest().getCookies();
        HttpCookie cookie = cookies.getFirst("token");
        if (cookie == null) {
            return chain.filter(exchange);
        } else {
            String token = cookie.getValue();
            String email = userFeignClientService.info(token);
            if ("".equals(email)) {
                response.setStatusCode(HttpStatus.SEE_OTHER);
                response.getHeaders().set(HttpHeaders.LOCATION, "http://www.test.com/static/login.html");
                return response.setComplete();
            } else {
                return chain.filter(exchange);
            }
        }
    }

    @Override
    public int getOrder() {
        return -1000;
    }
}